#include "productmanagementpanel.h"
#include <QTableWidget>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QMessageBox> // For placeholders

// Include C backend header for drinks
extern "C" {
#include "../backend/drink.h"
}

ProductManagementPanel::ProductManagementPanel(QWidget *parent)
    : QWidget(parent)
{
    setupUi();
    loadProducts(); // Load products initially
}

ProductManagementPanel::~ProductManagementPanel()
{
    freeProductList(); // Free memory when panel is destroyed
}


void ProductManagementPanel::setupUi()
{
    // Table View for Products
    productTable = new QTableWidget();
    productTable->setColumnCount(6); // ID, Name, Category, Taste, Stock, Price
    productTable->setHorizontalHeaderLabels(QStringList() << "ID" << "名称" << "分类" << "口味" << "库存" << "价格");
    productTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    productTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    productTable->setSelectionMode(QAbstractItemView::SingleSelection);
    productTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // Buttons
    btnAdd = new QPushButton("➕ 添加商品");
    btnEdit = new QPushButton("✏️ 编辑商品");
    btnDelete = new QPushButton("❌ 删除商品");
    btnRefresh = new QPushButton("🔄 刷新列表");

    // Product Count Label
    lblProductCount = new QLabel("总商品数：0");

    // Layouts
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addWidget(btnAdd);
    buttonLayout->addWidget(btnEdit);
    buttonLayout->addWidget(btnDelete);
    buttonLayout->addStretch();
    buttonLayout->addWidget(btnRefresh);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(productTable);
    mainLayout->addWidget(lblProductCount, 0, Qt::AlignRight);

    // Connections
    connect(btnRefresh, &QPushButton::clicked, this, &ProductManagementPanel::loadProducts);
    connect(btnAdd, &QPushButton::clicked, this, &ProductManagementPanel::addProduct);
    connect(btnEdit, &QPushButton::clicked, this, &ProductManagementPanel::editProduct);
    connect(btnDelete, &QPushButton::clicked, this, &ProductManagementPanel::deleteProduct);
    connect(productTable, &QTableWidget::itemDoubleClicked, this, &ProductManagementPanel::editProduct); // Double click to edit
}

void ProductManagementPanel::loadProducts()
{
    freeProductList(); // Free previous list
    int count = load_drinks("drinks.dat", &productListHead); // Pass only filename
    lblProductCount->setText(QString("总商品数：%1").arg(count));
    populateTable();
}

void ProductManagementPanel::populateTable()
{
    clearTable();
    DrinkNode* current = productListHead;
    int row = 0;
    while (current != nullptr) {
        productTable->insertRow(row);
        productTable->setItem(row, 0, new QTableWidgetItem(QString::number(current->data.id)));
        productTable->setItem(row, 1, new QTableWidgetItem(QString::fromUtf8(current->data.name)));
        productTable->setItem(row, 2, new QTableWidgetItem(QString::fromUtf8(current->data.category)));
        productTable->setItem(row, 3, new QTableWidgetItem(QString::fromUtf8(current->data.taste)));
        productTable->setItem(row, 4, new QTableWidgetItem(QString::number(current->data.stock)));
        productTable->setItem(row, 5, new QTableWidgetItem(QString::number(current->data.price, 'f', 2)));
        // Store product ID in the first column's item data for easy retrieval
        productTable->item(row, 0)->setData(Qt::UserRole, current->data.id);
        current = current->next;
        row++;
    }
}

void ProductManagementPanel::clearTable()
{
    productTable->clearContents();
    productTable->setRowCount(0);
}

void ProductManagementPanel::freeProductList()
{
    if (productListHead) {
        free_all_drinks(productListHead);
        productListHead = nullptr;
    }
}

#include <QDialog>
#include <QLineEdit>
#include <QDoubleValidator>
#include <QIntValidator>
#include <QFormLayout>
#include <QDialogButtonBox>

// 内部弹窗类：用于新增商品
class ProductDialog : public QDialog {
public:
    QLineEdit* idEdit;
    QLineEdit* nameEdit;
    QLineEdit* categoryEdit;
    QLineEdit* tasteEdit;
    QLineEdit* stockEdit;
    QLineEdit* priceEdit;
    bool isEditMode; // Flag to indicate if dialog is for editing

    // Constructor for Adding (pass nullptr for drinkData) or Editing
    ProductDialog(const Drink* drinkData = nullptr, QWidget *parent = nullptr)
        : QDialog(parent), isEditMode(drinkData != nullptr)
    {
        setWindowTitle(isEditMode ? "编辑商品" : "添加商品");
        QFormLayout* form = new QFormLayout(this);
        idEdit = new QLineEdit; idEdit->setValidator(new QIntValidator(1, 100000, this)); form->addRow("编号:", idEdit);
        nameEdit = new QLineEdit; form->addRow("名称:", nameEdit);
        categoryEdit = new QLineEdit; form->addRow("分类:", categoryEdit);
        tasteEdit = new QLineEdit; form->addRow("口味:", tasteEdit);
        stockEdit = new QLineEdit; stockEdit->setValidator(new QIntValidator(0, 100000, this)); form->addRow("库存:", stockEdit);
        priceEdit = new QLineEdit; priceEdit->setValidator(new QDoubleValidator(0, 100000, 2, this)); form->addRow("价格:", priceEdit);

        if (isEditMode) {
            // Populate fields for editing
            idEdit->setText(QString::number(drinkData->id));
            idEdit->setReadOnly(true); // ID should not be editable
            nameEdit->setText(QString::fromUtf8(drinkData->name));
            categoryEdit->setText(QString::fromUtf8(drinkData->category));
            tasteEdit->setText(QString::fromUtf8(drinkData->taste));
            stockEdit->setText(QString::number(drinkData->stock));
            priceEdit->setText(QString::number(drinkData->price, 'f', 2));
        } else {
            // Set placeholder or default for adding
             idEdit->setPlaceholderText("输入正整数ID"); // Or auto-generate later
             idEdit->setReadOnly(false);
        }

        QDialogButtonBox* btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
        form->addWidget(btnBox);
        connect(btnBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
        connect(btnBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
    }

    // Helper function to get data from the dialog fields
    Drink getDrinkData() const {
        Drink drink = {}; // Initialize with zeros/empty strings
        drink.id = idEdit->text().toInt(); // ID is read-only in edit mode, but we still read it
        strncpy(drink.name, nameEdit->text().toUtf8().constData(), sizeof(drink.name) - 1);
        drink.name[sizeof(drink.name) - 1] = '\0';
        strncpy(drink.category, categoryEdit->text().toUtf8().constData(), sizeof(drink.category) - 1);
        drink.category[sizeof(drink.category) - 1] = '\0';
        strncpy(drink.taste, tasteEdit->text().toUtf8().constData(), sizeof(drink.taste) - 1);
        drink.taste[sizeof(drink.taste) - 1] = '\0';
        drink.stock = stockEdit->text().toInt();
        drink.price = priceEdit->text().toFloat();
        return drink;
    }
};

void ProductManagementPanel::addProduct()
{
    ProductDialog dlg(nullptr, this); // Pass nullptr for add mode
    if (dlg.exec() == QDialog::Accepted) {
        // 提取信息并检查
        Drink newDrink = dlg.getDrinkData(); // Use helper function

        // Basic Validation (ID check is slightly different for add)
        if (newDrink.id <= 0) {
             QMessageBox::warning(this, "输入错误", "编号必须为正整数！");
             return;
        }
        if (strlen(newDrink.name) == 0) {
            QMessageBox::warning(this, "输入错误", "名称不能为空！");
            return;
        }
        if (newDrink.stock < 0) {
            QMessageBox::warning(this, "输入错误", "库存须为非负整数！");
            return;
        }
        if (newDrink.price < 0) {
            QMessageBox::warning(this, "输入错误", "价格须为不小于0的数字！");
            return;
        }

        // 检查编号冲突 (Only for adding)
        if (find_drink_by_id(productListHead, newDrink.id)) {
            QMessageBox::warning(this, "添加失败", "已存在相同编号的商品！");
            return;
        }
        // 插入到C链表
        if (!add_drink(&productListHead, &newDrink)) {
            QMessageBox::critical(this, "错误", "添加失败，链表操作异常。");
            return;
        }
        // 持久化到文件
        if (!save_drinks("drinks.dat", productListHead)) { // Pass only filename
            QMessageBox::critical(this, "保存失败", "写入文件时发生错误。");
            // Consider how to handle save failure - maybe remove the added item from memory?
            // For now, just return and the table won't reflect the failed add.
            // Reloading might be confusing here if the add succeeded in memory but failed to save.
            return;
        }
        loadProducts(); // 刷新
        QMessageBox::information(this, "成功", "商品添加成功！");
    }
}

void ProductManagementPanel::editProduct()
{
    QList<QTableWidgetItem*> selectedItems = productTable->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要编辑的商品！");
        return;
    }

    int selectedRow = selectedItems.first()->row();
    int productId = productTable->item(selectedRow, 0)->data(Qt::UserRole).toInt();

    // Find the product node in the memory list
    DrinkNode* productNode = find_drink_by_id(productListHead, productId);
    if (!productNode) {
        QMessageBox::critical(this, "错误", "无法在内存中找到所选商品！请刷新列表。");
        return;
    }

    // Show the dialog in edit mode, pre-filled with current data
    ProductDialog dlg(&productNode->data, this);
    if (dlg.exec() == QDialog::Accepted) {
        Drink updatedDrink = dlg.getDrinkData(); // Get data from dialog

        // Basic Validation
        if (strlen(updatedDrink.name) == 0) {
            QMessageBox::warning(this, "输入错误", "名称不能为空！");
            return;
        }
        if (updatedDrink.stock < 0) {
            QMessageBox::warning(this, "输入错误", "库存须为非负整数！");
            return;
        }
        if (updatedDrink.price < 0) {
            QMessageBox::warning(this, "输入错误", "价格须为不小于0的数字！");
            return;
        }
        // Note: ID is read-only, so no need to validate/check conflict for ID

        // Update the node in the memory list
        if (update_drink(productListHead, &updatedDrink)) {
            // Save the updated list back to file
            if (save_drinks("drinks.dat", productListHead)) {
                QMessageBox::information(this, "成功", QString("商品 '%1' 更新成功！").arg(QString::fromUtf8(updatedDrink.name)));
                loadProducts(); // Reload table to show the updated product
            } else {
                QMessageBox::critical(this, "错误", "保存商品数据失败！");
                loadProducts(); // Reload to reflect state before failed save
            }
        } else {
             QMessageBox::critical(this, "错误", "更新商品内存数据失败！");
             loadProducts(); // Reload
        }
    }
}

void ProductManagementPanel::deleteProduct()
{
    QList<QTableWidgetItem*> selectedItems = productTable->selectedItems();
    if (selectedItems.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先选择要删除的商品！");
        return;
    }

    int selectedRow = selectedItems.first()->row();
    int productId = productTable->item(selectedRow, 0)->data(Qt::UserRole).toInt();
    QString productName = productTable->item(selectedRow, 1)->text();

    // Confirmation dialog
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认删除", QString("确定要删除商品 '%1' (ID: %2) 吗？此操作不可恢复！").arg(productName).arg(productId),
                                QMessageBox::Yes|QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        // Delete product from the memory list
        if (delete_drink(&productListHead, productId)) { // Pass address of head pointer
            // Save the updated list back to file
            if (save_drinks("drinks.dat", productListHead)) {
                QMessageBox::information(this, "成功", QString("商品 '%1' 删除成功！").arg(productName));
                loadProducts(); // Reload table to reflect deletion
            } else {
                QMessageBox::critical(this, "错误", "保存商品数据失败！");
                // Attempt to reload data to restore consistency if save failed after delete
                loadProducts();
            }
        } else {
             QMessageBox::critical(this, "错误", "删除商品内存数据失败！可能已被删除，请刷新。");
             loadProducts(); // Reload
        }
    }
}